package com.example.SBootDemo.service.Imp.function;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

import javax.persistence.Transient;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.example.SBootDemo.Dao.elock.AlarmMapper;
import com.example.SBootDemo.Dao.elock.AlarmTypeMapper;
import com.example.SBootDemo.Dao.elock.BindDeviceMapper;
import com.example.SBootDemo.Dao.elock.CommandIssuedHistoryMapper;
import com.example.SBootDemo.Dao.elock.CommandIssuedMapper;
import com.example.SBootDemo.Dao.elock.DeviceDataMapper;
import com.example.SBootDemo.Dao.elock.DeviceHeartbeatMapper;
import com.example.SBootDemo.Dao.elock.DeviceMapper;
import com.example.SBootDemo.Dao.elock.FenceGroupMapper;
import com.example.SBootDemo.Dao.elock.FenceGroupRelationMapper;
import com.example.SBootDemo.Dao.elock.FenceMapper;
import com.example.SBootDemo.Dao.elock.MonitoringObjectMapper;
import com.example.SBootDemo.Dao.elock.MqttDataMapper;
import com.example.SBootDemo.model.elock.Alarm;
import com.example.SBootDemo.model.elock.BindDevice;
import com.example.SBootDemo.model.elock.CommandIssued;
import com.example.SBootDemo.model.elock.CommandIssuedHistory;
import com.example.SBootDemo.model.elock.Device;
import com.example.SBootDemo.model.elock.DeviceData;
import com.example.SBootDemo.model.elock.DeviceHeartbeat;
import com.example.SBootDemo.model.elock.FenceGroup;
import com.example.SBootDemo.model.elock.MonitoringObject;
import com.example.SBootDemo.model.elock.MqttData;
import com.example.SBootDemo.service.Interface.function.deviceInterface;

import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;
@Service
public class deviceImpl implements deviceInterface {

	@Autowired
	DeviceDataMapper deviceserver;
	
	@Autowired
	MqttDataMapper mqttserver;
	
	@Autowired
	DeviceHeartbeatMapper heartserver;
	
	@Autowired
	CommandIssuedMapper cmd;
	@Autowired
	CommandIssuedHistoryMapper cmdhistory;
	
	@Autowired
	AlarmMapper alarm;
	@Autowired
	AlarmTypeMapper alarmtype;
	@Autowired
	FenceMapper fence;
	@Autowired
	FenceGroupMapper fencegroup;
	@Autowired
	FenceGroupRelationMapper fencegrouprelation;
	@Autowired
	DeviceMapper device;
	@Autowired
	MonitoringObjectMapper monitoringobject;
	@Autowired
	BindDeviceMapper binddevice;
	
	
	
	/***
	 * {
	"abnormalOpening": false,
	"autoShutdown": false,
	"charging": false,
	"cutWire": true,
	"deviceRun": true,
	"distanceTooClose": false,
	"electricSupplyDisconnect": false,
	"g4Closed": true,
	"gpsClosed": true,
	"gpsInterference": false,
	"illegalEntry": true,
	"leaveHome": false,
	"loginException": false,
	"loraInterference": false,
	"lowBattery10": false,
	"lowBattery20": false,
	"quickMove": false,
	"signLevel": "无信号",
	"sosAlarm": false,
	"stationDisassembly": false,
	"watchDisassembly": true
	}
	 * 
	"abnormalOpening": false,
	"autoShutdown": false,
	"charging": false,
	"cutWire": false,
	"deviceRun": true,
	"distanceTooClose": false,
	"electricSupplyDisconnect": false,
	"g4Closed": true,
	"gpsClosed": true,
	"gpsInterference": false,
	"illegalEntry": true,
	"leaveHome": false,
	"loginException": false,
	"loraInterference": false,
	"lowBattery10": false,
	"lowBattery20": false,
	"quickMove": false,
	"signLevel": "无信号",
	"sosAlarm": false,
	"stationDisassembly": false,
	"watchDisassembly": true
	 * 
	 * 
	 * 
	 * 
	 * 
	"autoShutdown": false,自动关机
	"charging": false,充电
	"cutWire": false,剪断
	"deviceRun": true,设备运行
	"distanceTooClose": false,接近告警
	"entryStation": true,进入基站
	"externalDisconnection": false,市电断
	"g4Closed": true, 4G关闭
	"gpsClosed": true,GPS关闭
	"gpsInterference": false,GPS被干扰
	"illegalEntry": false,非法进入基站
	"leaveHome": false,非法离开/离家
	"loginException": false,登陆异常
	"loraDamage": false,LORA损坏
	"loraInterference": false,LORA被干扰
	"lowBattery10": false,低电量10
	"lowBattery20": false,低电量20
	"openLid": false,开盖告警
	"quickMove": false,快速移动
	"signLevel": "无信号",信号
	"sosAlarm": false,sos告警
	"stationDisassembly": false,基站拆卸
	"stationOpenLid": false,基站开盖
	"watchDisassembly": false  腕带拆卸
	 * 
	 * 
	 * */
  
	@SuppressWarnings("null")
	@Override
	public List<DeviceData> getDeviceInfo(String deviceID, String startDate, String EndDate) {
		// TODO Auto-generated method stub
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			if(deviceID.equals("")) {
				deviceID="zsd";
			}
			Date s_date1=new Date();
			Date s_date2=new Date();
		if(startDate.equals("1")||EndDate.equals("1")) {
	        long current=System.currentTimeMillis();//当前时间毫秒数
	        long zero=current/(1000*3600*24)*(1000*3600*24)-TimeZone.getDefault().getRawOffset();//今天零点零分零秒的毫秒数
	        long twelve=zero+24*60*60*1000-1;//今天23点59分59秒的毫秒数
	       
	        s_date1.setTime(zero);
	        s_date2.setTime(twelve);
		}else {

		try {
			 s_date1 =(Date)sdf.parse(startDate+" 00:00:00");
			 s_date2 =(Date)sdf.parse(EndDate+" 23:59:59");
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		}
		Example example = new Example(DeviceData.class); 
		example.setOrderByClause("data_upload_datetime desc");
		Criteria criteria = example.createCriteria();
		criteria.andLike("deviceId", "%"+deviceID+"%");
		criteria.andBetween("dataUploadDatetime", s_date1, s_date2);
		List<DeviceData> list=new ArrayList<>();
		list = deviceserver.selectByExample(example);
		for (int i = 0; i < list.size(); i++) {
			String remarke = list.get(i).getRemark();
			String remarkeinfo = "";
			JSONObject rowData = JSONObject.parseObject(remarke);
			if(rowData.get("entryStation").equals(true)) {
				remarkeinfo+="进入基站/";
			}
			 if(rowData.get("autoShutdown").equals(true)) {
				remarkeinfo+="自动关机/";
			}
			 if(rowData.get("charging").equals(true)) {
				remarkeinfo+="充电中/";
			}
			 if(rowData.get("cutWire").equals(true)) {
				remarkeinfo+="剪断/";
			}
			 if(rowData.get("openLid").equals(true)) {
				remarkeinfo+="镣铐开盖/";
			}
			 if(rowData.get("deviceRun").equals(true)) {
				remarkeinfo+="设备运行/";
			}
			 if(rowData.get("distanceTooClose").equals(true)) {
				remarkeinfo+="距离过近/";
			}
			 if(rowData.get("externalDisconnection").equals(true)) {
				remarkeinfo+="市电断/";
			}
			 if(rowData.get("g4Closed").equals(true)) {
				remarkeinfo+="4G关闭/";
			}
			 if(rowData.get("gpsClosed").equals(true)) {
				remarkeinfo+="GPS关闭/";
			}
			 if(rowData.get("gpsInterference").equals(true)) {
				remarkeinfo+="GPS被干扰/";
			}
			 if(rowData.get("illegalEntry").equals(true)) {
				remarkeinfo+="非法进入基站/";
			}
			 if(rowData.get("leaveHome").equals(true)) {
				remarkeinfo+="离家/";
			}
			 if(rowData.get("loginException").equals(true)) {
				remarkeinfo+="登陆错误/";
			}
			 if(rowData.get("loraInterference").equals(true)) {
				remarkeinfo+="LORA被干扰/";
			}
			 if(rowData.get("lowBattery10").equals(true)) {
				remarkeinfo+="低电量10/";
			}
			 if(rowData.get("lowBattery20").equals(true)) {
				remarkeinfo+="低电量20/";
			}
			 if(rowData.get("quickMove").equals(true)) {
				remarkeinfo+="快速移动/";
			}
			 if(rowData.get("signLevel").equals(true)) {
				remarkeinfo+="无信号/";
			}
			 if(rowData.get("sosAlarm").equals(true)) {
				remarkeinfo+="SOS告警/";
			}
			 if(rowData.get("stationDisassembly").equals(true)) {
				remarkeinfo+="基站拆除/";
			}
			 if(rowData.get("stationOpenLid").equals(true)) {
				remarkeinfo+="基站开盖/";
			}
			 if(rowData.get("watchDisassembly").equals(true)) {
				remarkeinfo+="腕带拆卸/";
			}
			 if(rowData.get("loraDamage").equals(true)) {
				remarkeinfo+="LORA坏/";
			}
			list.get(i).setRemarkInfo(remarkeinfo);
		}
		
		return list;
	}

	

	@Override
	public List<MqttData> getMqttDataByUpdate(Long id,int tip) {
		// TODO Auto-generated method stub
		Object obj = new Object();
		if(tip==1) {
			DeviceData device_data=   deviceserver.selectByPrimaryKey(id);
			Example example = new Example(MqttData.class); 
			Criteria criteria = example.createCriteria();
			criteria.andEqualTo("dataUploadDatetime", device_data.getDataUploadDatetime());
			
			return mqttserver.selectByExample(example);
		}else if(tip==2){
			DeviceHeartbeat device_data=   heartserver.selectByPrimaryKey(id);
			Example example = new Example(MqttData.class); 
			Criteria criteria = example.createCriteria();
			criteria.andEqualTo("dataUploadDatetime", device_data.getDataUploadDatetime());
			
			return mqttserver.selectByExample(example);
		}else if(tip==4) {
			Alarm device_data=   alarm.selectByPrimaryKey(id);
			Example example = new Example(MqttData.class); 
			Criteria criteria = example.createCriteria();
			criteria.andEqualTo("dataUploadDatetime", device_data.getAlarmDatetime());
			return mqttserver.selectByExample(example);
		}else {
			return null;
		}
		
	}
	
	



	@Override
	public List<DeviceHeartbeat> getDeviceHeartInfo(String deviceID, String startDate, String EndDate) {
		// TODO Auto-generated method stub
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		Date s_date1=new Date();
		Date s_date2=new Date();
	if(startDate.equals("1")||EndDate.equals("1")) {
        long current=System.currentTimeMillis();//当前时间毫秒数
        long zero=current/(1000*3600*24)*(1000*3600*24)-TimeZone.getDefault().getRawOffset();//今天零点零分零秒的毫秒数
        long twelve=zero+24*60*60*1000-1;//今天23点59分59秒的毫秒数
       
        s_date1.setTime(zero);
        s_date2.setTime(twelve);
	}else {

	try {
		 s_date1 =(Date)sdf.parse(startDate+" 00:00:00");
		 s_date2 =(Date)sdf.parse(EndDate+" 23:59:59");
	} catch (ParseException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	}
	Example example = new Example(DeviceHeartbeat.class); 
	example.setOrderByClause("data_upload_datetime desc");
	Criteria criteria = example.createCriteria();
	criteria.andLike("deviceId", "%"+deviceID+"%");
	criteria.andBetween("dataUploadDatetime", s_date1, s_date2);
	List<DeviceHeartbeat> list=new ArrayList<>();
	list = heartserver.selectByExample(example);
	for (int i = 0; i < list.size(); i++) {
		String remarke = list.get(i).getRemark();
		String remarkeinfo = "";
		JSONObject rowData = JSONObject.parseObject(remarke);
		if(rowData.get("entryStation").equals(true)) {
			remarkeinfo+="进入基站/";
		}
		 if(rowData.get("autoShutdown").equals(true)) {
			remarkeinfo+="自动关机/";
		}
		 if(rowData.get("charging").equals(true)) {
			remarkeinfo+="充电中/";
		}
		 if(rowData.get("cutWire").equals(true)) {
			remarkeinfo+="剪断/";
		}
		 if(rowData.get("openLid").equals(true)) {
			remarkeinfo+="镣铐开盖/";
		}
		 if(rowData.get("deviceRun").equals(true)) {
			remarkeinfo+="设备运行/";
		}
		 if(rowData.get("distanceTooClose").equals(true)) {
			remarkeinfo+="距离过近/";
		}
		 if(rowData.get("externalDisconnection").equals(true)) {
			remarkeinfo+="市电断/";
		}
		 if(rowData.get("g4Closed").equals(true)) {
			remarkeinfo+="4G关闭/";
		}
		 if(rowData.get("gpsClosed").equals(true)) {
			remarkeinfo+="GPS关闭/";
		}
		 if(rowData.get("gpsInterference").equals(true)) {
			remarkeinfo+="GPS被干扰/";
		}
		 if(rowData.get("illegalEntry").equals(true)) {
			remarkeinfo+="非法进入基站/";
		}
		 if(rowData.get("leaveHome").equals(true)) {
			remarkeinfo+="离家/";
		}
		 if(rowData.get("loginException").equals(true)) {
			remarkeinfo+="登陆错误/";
		}
		 if(rowData.get("loraInterference").equals(true)) {
			remarkeinfo+="LORA被干扰/";
		}
		 if(rowData.get("lowBattery10").equals(true)) {
			remarkeinfo+="低电量10/";
		}
		 if(rowData.get("lowBattery20").equals(true)) {
			remarkeinfo+="低电量20/";
		}
		 if(rowData.get("quickMove").equals(true)) {
			remarkeinfo+="快速移动/";
		}
		 if(rowData.get("signLevel").equals(true)) {
			remarkeinfo+="无信号/";
		}
		 if(rowData.get("sosAlarm").equals(true)) {
			remarkeinfo+="SOS告警/";
		}
		 if(rowData.get("stationDisassembly").equals(true)) {
			remarkeinfo+="基站拆除/";
		}
		 if(rowData.get("stationOpenLid").equals(true)) {
			remarkeinfo+="基站开盖/";
		}
		 if(rowData.get("watchDisassembly").equals(true)) {
			remarkeinfo+="腕带拆卸/";
		}
		 if(rowData.get("loraDamage").equals(true)) {
			remarkeinfo+="LORA坏/";
		}
		 list.get(i).setRemarkInfo(remarkeinfo);
	}
	
	return list;
	}



	@Override
	public List<CommandIssued> getDeviceCmd(String deviceID, String startDate, String EndDate) {
		// TODO Auto-generated method stub
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date s_date1=new Date();
		Date s_date2=new Date();
		Example example = new Example(CommandIssued.class); 
		example.setOrderByClause("create_time desc");
		Criteria criteria = example.createCriteria();
		criteria.andLike("deviceId", "%"+deviceID+"%");
	if(!startDate.equals("1")||!EndDate.equals("1")) {


		try {
			 s_date1 =(Date)sdf.parse(startDate+" 00:00:00");
			 s_date2 =(Date)sdf.parse(EndDate+" 23:59:59");
			 criteria.andBetween("createTime", s_date1, s_date2);
		}catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	
	List<CommandIssued> list=new ArrayList<>();
	list = cmd.selectByExample(example);
	return list;
	}



	@Override
	public List<CommandIssuedHistory> getDeviceCmdHistory(String deviceID, String startDate, String EndDate) {
		// TODO Auto-generated method stub
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date s_date1=new Date();
		Date s_date2=new Date();
		Example example = new Example(CommandIssued.class); 
		example.setOrderByClause("create_time desc");
		Criteria criteria = example.createCriteria();
		criteria.andLike("deviceId", "%"+deviceID+"%");
	if(!startDate.equals("1")||!EndDate.equals("1")) {


		try {
			 s_date1 =(Date)sdf.parse(startDate+" 00:00:00");
			 s_date2 =(Date)sdf.parse(EndDate+" 23:59:59");
			 criteria.andBetween("createTime", s_date1, s_date2);
		}catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	
	List<CommandIssuedHistory> list=new ArrayList<>();
	list = cmdhistory.selectByExample(example);
	return list;
	}



	@Override
	public List<Alarm> getDeviceAlarm(String deviceID, String startDate, String EndDate, String alarmType) {
		// TODO Auto-generated method stub
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if(deviceID.equals("")) {
			deviceID="zsd";
		}
		Date s_date1=new Date();
		Date s_date2=new Date();
	if(startDate.equals("1")||EndDate.equals("1")) {
        long current=System.currentTimeMillis();//当前时间毫秒数
        long zero=current/(1000*3600*24)*(1000*3600*24)-TimeZone.getDefault().getRawOffset();//今天零点零分零秒的毫秒数
        long twelve=zero+24*60*60*1000-1;//今天23点59分59秒的毫秒数
       
        s_date1.setTime(zero);
        s_date2.setTime(twelve);
	}else {

	try {
		 s_date1 =(Date)sdf.parse(startDate+" 00:00:00");
		 s_date2 =(Date)sdf.parse(EndDate+" 23:59:59");
	} catch (ParseException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	}
	Example example = new Example(Alarm.class); 
	example.setOrderByClause("alarm_datetime desc");
	Criteria criteria = example.createCriteria();
	criteria.andLike("deviceId", "%"+deviceID+"%");
	criteria.andLike("name", "%"+alarmType+"%");
	criteria.andBetween("alarmDatetime", s_date1, s_date2);
	List<Alarm> list=new ArrayList<>();
	list = alarm.selectByExample(example);
	for (int i = 0; i < list.size(); i++) {
		Long typeid = list.get(i).getAlarmTypeId();
		list.get(i).setName(alarmtype.selectByPrimaryKey(typeid).getName()); 
		if(list.get(i).getFenceId()!=null) {
		list.get(i).setFenceName(fence.selectByPrimaryKey(list.get(i).getFenceId()).getName());
		}
	}

	return list;
	}



	@Override
	public List<MqttData> getDeviceMq(String deviceID, String startDate, String EndDate,String topType) {
		// TODO Auto-generated method stub
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if(deviceID.equals("")) {
			deviceID="zsd";
		}
		Date s_date1=new Date();
		Date s_date2=new Date();
	if(startDate.equals("1")||EndDate.equals("1")) {
        long current=System.currentTimeMillis();//当前时间毫秒数
        long zero=current/(1000*3600*24)*(1000*3600*24)-TimeZone.getDefault().getRawOffset();//今天零点零分零秒的毫秒数
        long twelve=zero+24*60*60*1000-1;//今天23点59分59秒的毫秒数
       
        s_date1.setTime(zero);
        s_date2.setTime(twelve);
	}else {

	try {
		 s_date1 =(Date)sdf.parse(startDate+" 00:00:00");
		 s_date2 =(Date)sdf.parse(EndDate+" 23:59:59");
	} catch (ParseException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	}
	Example example = new Example(MqttData.class); 
	example.setOrderByClause("create_time desc");
	Criteria criteria = example.createCriteria();
	criteria.andLike("topic", "%"+deviceID+"%");
	criteria.andLike("topic", "%"+topType+"%");
	criteria.andBetween("createTime", s_date1, s_date2);
	List<MqttData> list=new ArrayList<>();
	list = mqttserver.selectByExample(example);
	for (int i = 0; i < list.size(); i++) {
		String topStr = list.get(i).getTopic();

		if(topStr.contains("HB")) {
			list.get(i).setTypeId("HB");
		}else if(topStr.contains("RG")) {
			list.get(i).setTypeId("RG");
		}else if(topStr.contains("DT")) {
			list.get(i).setTypeId("DT");
		}else if(topStr.contains("AL")) {
			list.get(i).setTypeId("AL");
		}else if(topStr.contains("CM")) {
			list.get(i).setTypeId("CM");
		}else if(topStr.contains("BK")) {
			list.get(i).setTypeId("BK");
		}else if(topStr.contains("LC")) {
			list.get(i).setTypeId("LC");
		}
		
	}
	
	return list;
	}



	@Override
	public List<MonitoringObject> getObjecttoDevice(String firstname,String secondname) {
		Example example = new Example(MonitoringObject.class); 
		Criteria criteria = example.createCriteria();
		criteria.andLike("firstName", "%"+firstname+"%");
		criteria.andLike("secondName", "%"+secondname+"%");
		List<MonitoringObject> object = monitoringobject.selectByExample(example);
		for(int i=0;i<object.size();i++) {
			Example BindDevice = new Example(BindDevice.class); 
			Criteria BindDevicecr = BindDevice.createCriteria();
			BindDevicecr.andEqualTo("monitoringObjectId",object.get(i).getId());
			BindDevicecr.andIsNull("releaseTime");
			List<BindDevice> bind = binddevice.selectByExample(BindDevice);
			for(int a=0;a<bind.size();a++) {
				Example Device1 = new Example(Device.class); 
				Criteria Devicecr = Device1.createCriteria();
				Devicecr.andEqualTo("deviceId",bind.get(a).getDeviceId());
				if(device.selectByExample(Device1).size()>0) {
					object.get(i).getDevice().add(device.selectByExample(Device1).get(0));
				}
				
			}
			
		}
		// TODO Auto-generated method stub
		
		return object;
	}



	@Override
	public List<Device> getDevicetoObject(String deviceID) {
		// TODO Auto-generated method stub
		Example example = new Example(Device.class); 
		Criteria criteria = example.createCriteria();
		criteria.andLike("deviceId", "%"+deviceID+"%");
		List<Device> d = device.selectByExample(example);
		for(int i=0;i<d.size();i++) {
			Example BindDevice = new Example(BindDevice.class); 
			Criteria BindDevicecr = BindDevice.createCriteria();
			BindDevicecr.andEqualTo("deviceId",d.get(i).getDeviceId());
			BindDevicecr.andIsNull("releaseTime");
			List<BindDevice> bind = binddevice.selectByExample(BindDevice);
			for(int a=0;a<bind.size();a++) {
				Example Device1 = new Example(MonitoringObject.class); 
				Criteria Devicecr = Device1.createCriteria();
				Devicecr.andEqualTo("id",bind.get(a).getMonitoringObjectId());
				if(monitoringobject.selectByExample(Device1).size()>0) {
					d.get(i).getMonitoringObject().add(monitoringobject.selectByExample(Device1).get(0));
				}
				
			}
			
		}
		// TODO Auto-generated method stub
		
		return d;
	}
}
